//
//  AlbumDetailViewController.m
//  聆听FM
//
//  Created by dllo on 16/6/12.
//  Copyright © 2016年 Dark. All rights reserved.
//

#import "AlbumDetailViewController.h"
#import "ZCSAlbumHeaderTableViewCell.h"
#import "ZCSSpecialModel.h"
#import "ZCSSpecialItemModel.h"
#import "ZCSLabelCollectionViewCell.h"
#import "YFRollingLabel.h"
#import "ZCSAlbumTopTableViewCell.h"
#import "ZCSAlbumListNoXibTableViewCell.h"
#import "ZCSListenListListModel.h"
#import "ZCSPlayMusicViewController.h"
//#import "ZCSAlbumSetTableViewCell.h"
#import "LTDataBase.h"

@interface AlbumDetailViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, copy) NSString *asc;
@property (nonatomic, retain) NSMutableArray *dataArray;
@property (nonatomic, retain) ZCSSpecialModel *specialModel;
@property (nonatomic, retain) ZCSSpecialItemModel *itemModel;
@property (nonatomic, retain) ZCSAlbumHeaderTableViewCell *header;
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) UIView *cvBackView;
@property (nonatomic, assign) BOOL isDided;

@property (nonatomic, assign) NSInteger itemNum;

@property (nonatomic, assign) NSInteger isSelect;

@property (nonatomic, retain) UIView *tableHeader;
@property (nonatomic, retain) UIImageView *headerBackImage;
@property (nonatomic, retain) YFRollingLabel *rollingLabel;

@property (nonatomic, retain) ZCSAlbumTopTableViewCell *topView;

@property (nonatomic, retain) NSMutableArray *playArray;

@property (nonatomic, retain) NSMutableArray *tempArray;

@property (nonatomic, retain) UIBarButtonItem *collect;

@property (nonatomic, assign) BOOL isCollect;

@end

@implementation AlbumDetailViewController
- (void)dealloc
{
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
    _collectionView.delegate = nil;
    _collectionView.dataSource = nil;
    [self removeObserver:self forKeyPath:@"isCollect"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"专辑详情";
    self.navigationController.navigationBar.translucent = NO;
    
    self.collect = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"noCollect"] imageWithRenderingMode:1] style:UIBarButtonItemStylePlain target:self action:@selector(didClickCollect:)];
    
    self.navigationItem.rightBarButtonItem = self.collect;
    self.view.backgroundColor = [UIColor whiteColor];
    self.dataArray = [NSMutableArray array];
    self.playArray = [NSMutableArray array];
    self.tempArray = [NSMutableArray array];
    [self creatView];
    self.page = 1;
    self.asc = @"true";
    [self getDataWith:self.albmId];
    
    [self addObserver:self forKeyPath:@"isCollect" options:NSKeyValueObservingOptionNew context:nil];
    
  //  [self getDataWith:self.albmId Page:self.page ASC:self.asc];
}


- (void)viewWillAppear:(BOOL)animated
{
    LTDataBase *data = [LTDataBase shareLTDataBaseTool];
  NSInteger num = [data isSaveDataInTableWithModel_id:self.albmId type:0];
    if (num == 0) {
        self.isCollect = YES;
    }
    else
    {
        self.isCollect = NO;
    }
    self.navigationController.navigationBar.hidden = NO;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([[change objectForKey:@"new"] boolValue] == NO) {
        self.collect.image = [[UIImage imageNamed:@"noCollect"] imageWithRenderingMode:1];
    }
    else
    {
        self.collect.image = [[UIImage imageNamed:@"collect"] imageWithRenderingMode:1];
    }
}

- (void)didClickCollect:(UIBarButtonItem *)button
{
    if (_isCollect == NO) {
        self.collect.image = [[UIImage imageNamed:@"collect"] imageWithRenderingMode:1];
        self.isCollect = YES;
        [MBProgressHUD showSuccess:@"已添加关注"];
        LTDataBase *data = [LTDataBase shareLTDataBaseTool];
        [data insertDataWithAlbumModel:self.albumModel];
    }
    else
    {
        self.collect.image = [[UIImage imageNamed:@"noCollect"] imageWithRenderingMode:1];
        self.isCollect = NO;
        [MBProgressHUD showSuccess:@"已取消关注"];
        LTDataBase *data = [LTDataBase shareLTDataBaseTool];
        [data delegateDataWithModel_id:self.albumModel.albumId type:0];
    }
    
}




#pragma mark ---头视图
- (void)HeaderView
{
    self.tableHeader = [[UIView alloc] initWithFrame:CGRectMake( 0, 0, SCREENWIDTH, 250 * FITHEIGHT)];
    self.tableHeader.backgroundColor = [UIColor colorWithWhite:0.908 alpha:1.000];
    self.tableView.tableHeaderView = self.tableHeader;
    self.headerBackImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 240 * FITHEIGHT)];
    self.headerBackImage.backgroundColor = [UIColor redColor];
    //[self.headerBackImage sizeToFit];
    [self.tableHeader addSubview:_headerBackImage];
    
    
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:2];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    effectView.frame = self.headerBackImage.frame;
    [self.headerBackImage addSubview:effectView];
    
    ZCSAlbumTopTableViewCell *top = [self.tableView dequeueReusableCellWithIdentifier:@"topView"];
    top.backgroundColor = [UIColor clearColor];
    top.frame = self.headerBackImage.bounds;
    
    [self.headerBackImage addSubview:top];
    self.topView = top;
    
    
}

- (void)creatView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT - 64) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = 0;
    [self.view addSubview:_tableView];
    UIView *foot = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 80 * FITHEIGHT)];
    self.tableView.tableFooterView = foot;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCSAlbumHeaderTableViewCell" bundle:nil] forCellReuseIdentifier:@"albumHeader"];
    //[self.tableView registerNib:[UINib nibWithNibName:@"ZCSAlbumItemTableViewCell" bundle:nil] forCellReuseIdentifier:@"albumItem"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCSAlbumTopTableViewCell" bundle:nil] forCellReuseIdentifier:@"topView"];
    [self.tableView registerClass:[ZCSAlbumListNoXibTableViewCell class] forCellReuseIdentifier:@"albumItem"];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self getMoreData];
    }];
    [self HeaderView];
    [self creatCV];
}

- (void)creatCV
{
    UIView *cvBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 280 * FITHEIGHT, SCREENWIDTH, 0)];
    cvBackView.backgroundColor = [UIColor colorWithWhite:0.905 alpha:1.000];
    [self.tableView addSubview:cvBackView];
    self.cvBackView = cvBackView;
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake((SCREENWIDTH - 110 * FITWIDTH) / 4, 25 * FITHEIGHT);
    flowLayout.minimumLineSpacing = 10 * FITHEIGHT;
    flowLayout.minimumInteritemSpacing = 30 * FITWIDTH;
    flowLayout.sectionInset = UIEdgeInsetsMake(10 * FITHEIGHT, 10 * FITWIDTH, 10 * FITHEIGHT, 10 * FITWIDTH);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 0) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [cvBackView addSubview:_collectionView];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"ZCSLabelCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"labelCell"];
    
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.itemModel.totalCount / 20 + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZCSLabelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"labelCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithWhite:0.894 alpha:1.000];
    NSInteger num = self.itemNum - 20 * indexPath.row;
    if (num / 20 > 0) {
        NSString *tempString = [NSString stringWithFormat:@"%ld~%ld", 20 * indexPath.row + 1, 20 * indexPath.row + 20];
        cell.itemLabel.text = tempString;
    }
    else
    {
        NSString *tempString = [NSString stringWithFormat:@"%ld~%ld", 20 * indexPath.row + 1, self.itemModel.totalCount];
        cell.itemLabel.text = tempString;
    }
    
    if (indexPath.row == self.isSelect) {
        cell.backgroundColor = [UIColor colorWithRed:1.00 green:0.30 blue:0.24 alpha:1.00];
    }
    else
    {
        cell.backgroundColor = [UIColor colorWithRed:0.96 green:0.97 blue:0.98 alpha:1.00];
    }
    
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.isSelect = indexPath.row;
    self.page = indexPath.row + 1;
    [self getNewData];
    self.header.sortLabel.userInteractionEnabled = YES;
    self.collectionView.frame = CGRectMake(0, 0, SCREENWIDTH, 0);
    self.cvBackView.frame = CGRectMake(0, 30 * FITHEIGHT, SCREENWIDTH, 0);
    self.header.selectLabel.tag = 2000;
    [self.collectionView reloadData];
}


- (void)getNewData
{
    [self.dataArray removeAllObjects];
    [self.tableView reloadData];
    [self getDataWith:self.albmId Page:self.page ASC:self.asc];
}

- (void)getMoreData
{
    self.page++;
    if (self.page > self.itemModel.maxPageId) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    else
    {
     [self getDataWith:self.albmId Page:self.page ASC:self.asc];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.dataArray.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ZCSAlbumHeaderTableViewCell *header = [tableView dequeueReusableCellWithIdentifier:@"albumHeader"];
    header.numberLabel.text = [NSString stringWithFormat:@"共%ld集", self.specialModel.tracks];
    header.sortLabel.userInteractionEnabled = YES;
    if (_isDided) {
        header.sortImageView.image = [UIImage imageNamed:@"down"];
    }
    else
    {
        header.sortImageView.image = [UIImage imageNamed:@"up"];
    }
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sortImageAction:)];
    [header.sortLabel addGestureRecognizer:tap];
    header.selectLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *numTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(numberLabelAction:)];
    [header.selectLabel addGestureRecognizer:numTap];
    header.selectLabel.tag = 2000;
    self.header = header;
    return header;
}
- (void)numberLabelAction:(UITapGestureRecognizer *)tap
{
    NSInteger tempNum = self.itemModel.totalCount / 20 + 1;
    NSInteger num = tempNum / 4;
    CGFloat tempFloat = tempNum / 4.0;
    CGFloat height;
    if (tempFloat - num) {
        height = 25 * (num + 1) + 10 * (num + 2);
    }
    else
    {
        height = 25 * num + 10 * (num + 1);
    }
    if (self.header.selectLabel.tag == 2000) {
        self.header.sortLabel.userInteractionEnabled = NO;
//        //[UIView animateWithDuration:0.5 animations:^{
            self.collectionView.frame = CGRectMake(0, 0, SCREENWIDTH, height * FITHEIGHT);
           self.cvBackView.frame = CGRectMake(0, self.header.frame.origin.y + self.header.frame.size.height, SCREENWIDTH, SCREENHEIGHT - self.header.frame.origin.y + self.header.frame.size.height - 64);
//       // }];
       
        [self.dataArray addObjectsFromArray:self.tempArray];
         self.header.selectLabel.tag = 2001;
       
    }
    else
    {
        self.header.sortLabel.userInteractionEnabled = YES;
        self.collectionView.frame = CGRectMake(0, 0, SCREENWIDTH, 0);
        self.cvBackView.frame = CGRectMake(0, self.header.frame.origin.y + self.header.frame.size.height, SCREENWIDTH, 0);
       
        self.header.selectLabel.tag = 2000;
        
        
    
    }
    
}

#pragma mark -- 排序图片
- (void)sortImageAction:(UITapGestureRecognizer *)tap
{
    self.isDided = !_isDided;
    
    if (_isDided) {
       self.asc = @"false";
        self.page = 0;
        [self.dataArray removeAllObjects];
        [self.tableView reloadData];
        [self getMoreData];
    }
    else
    {
        self.asc = @"true";
        self.page = 0;
        [self.dataArray removeAllObjects];
        [self.tableView reloadData];
        [self getMoreData];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    ZCSSpecialListModel *model = [self.dataArray objectAtIndex:indexPath.row];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:13], NSFontAttributeName, nil];
    CGRect newRect = [model.title boundingRectWithSize:CGSizeMake(SCREENWIDTH - 140 * FITWIDTH, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return (newRect.size.height + 40) * FITHEIGHT;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30 * FITHEIGHT;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZCSAlbumListNoXibTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"albumItem"];
    cell.model = [self.dataArray objectAtIndex:indexPath.row];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZCSPlayMusicViewController *player = [ZCSPlayMusicViewController sharePlayVC];
    player.dataArray = self.playArray;
    player.musicIndex = indexPath.row;
    player.albumId = self.albmId;
    player.maxPage = self.itemModel.maxPageId;
    [self presentViewController:player animated:YES completion:nil];
    
}

- (void)getDataWith:(NSInteger)albumId
{
    NSString *url = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/v1/album?albumId=%ld&device=iPhone&pageSize=20&source=0&trackId=16978412", albumId];
    NSLog(@"%@", url);
    __weak AlbumDetailViewController *advc = self;
    [LTNetTool GetNetWithURL:url Body:nil Header:nil Response:0 Success:^(id result) {
        NSDictionary *dic = result[@"data"][@"album"];
         advc.specialModel = [[ZCSSpecialModel alloc] initWithDic:dic];
        advc.albumModel = [[LTAlbumModel alloc] initWithDic:dic];
        dic = result[@"data"][@"tracks"];
        if (dic) {
            for (NSDictionary *dict in dic[@"list"]) {
                ZCSListenListListModel *playModel = [[ZCSListenListListModel alloc] initWithDic:dict];
                [advc.playArray addObject:playModel];
            }
            advc.itemModel = [[ZCSSpecialItemModel alloc] initWithDic:dic];
            advc.itemNum = advc.itemModel.totalCount;
            [advc.dataArray addObjectsFromArray:advc.itemModel.list];
            [advc.tempArray addObjectsFromArray:advc.itemModel.list];
            [advc.tableView reloadData];
            [advc.headerBackImage sd_setImageWithURL:[NSURL URLWithString:advc.specialModel.coverLarge] placeholderImage:[UIImage sd_animatedGIFNamed:@"占位图"]];
            [advc.topView.headImageView sd_setImageWithURL:[NSURL URLWithString:advc.specialModel.coverMiddle] placeholderImage:[UIImage sd_animatedGIFNamed:@"占位图"]];
            advc.topView.titleLabel.text = [NSString stringWithFormat:@"%@", _specialModel.title];
            advc.topView.anchorLabel.text = [NSString stringWithFormat:@"主播:%@", _specialModel.nickname];
            advc.topView.playCountLabel.text = [NSString stringWithFormat:@"播放: %.1f万", _specialModel.playTimes / 10000.0];
            advc.topView.creatLabel.text = [advc getDataStringWith:_specialModel.createdAt];
            advc.topView.updataLabel.text = [NSString stringWithFormat:@"状态:%@更新", [advc getDataStringWith:_specialModel.updatedAt]];
            advc.topView.contectLabel.text = _specialModel.intro;
            NSMutableArray *array = [NSMutableArray array];
            [array addObject:_specialModel.title];
            [array addObject:_specialModel.title];
            [array addObject:_specialModel.title];
            [advc creatLabelWith:array];
            
            [advc.collectionView reloadData];
        }
        else
        {
            [MBProgressHUD showSuccess:@"对不起,该连接已失效"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [advc.navigationController popViewControllerAnimated:YES];
            });
            
        }
        
    } Failure:^(NSError *error) {
        NSLog(@"%@", error);
    }];

}
- (NSString *)getDataStringWith:(NSInteger)num
{
    NSString*str= [NSString stringWithFormat:@"%ld", num];//时间戳
    
    NSTimeInterval time=[str doubleValue]/1000;
    
    NSDate*detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    
    //实例化一个NSDateFormatter对象
    
    NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];
    
    //设定时间格式,这里可以设置成自己需要的格式
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString*currentDateStr = [dateFormatter stringFromDate:detaildate];
    //  NSLog(@"%@", currentDateStr);
    NSString *tempString = [currentDateStr substringWithRange:NSMakeRange(0, 10)];
    
    return tempString;
}

- (void)creatLabelWith:(NSArray *)textArray
{
    _rollingLabel = [[YFRollingLabel alloc] initWithFrame:CGRectMake(100 * FITWIDTH, 10, 175 * FITWIDTH, 24)  textArray:textArray font:[UIFont systemFontOfSize:17] textColor:[UIColor blackColor]];
    [self.navigationController.navigationBar addSubview:_rollingLabel];
    _rollingLabel.backgroundColor = [UIColor whiteColor];
    _rollingLabel.speed = 1;
    [_rollingLabel setOrientation:RollingOrientationLeft];
    [_rollingLabel setInternalWidth:_rollingLabel.frame.size.width / 3];
}

- (void)getDataWith:(NSInteger)albumId Page:(NSInteger)page ASC:(NSString *)asc
{
    
    NSString *urlString = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/v1/album/track?albumId=%ld&device=iPhone&isAsc=%@&pageId=%ld&pageSize=20&statEvent=pageview%%2Falbum%%40297108&statModule=猜你喜欢&statPage=tab%%40发现_推荐&statPosition=2", albumId, asc, page];
    __weak AlbumDetailViewController *advc = self;
    [LTNetTool GetNetWithURL:urlString Body:nil Header:nil Response:0 Success:^(id result) {
       
        NSDictionary *dic = result[@"data"];
        advc.itemModel = [[ZCSSpecialItemModel alloc] initWithDic:dic];
        [advc.dataArray addObjectsFromArray:advc.itemModel.list];
        [advc.tableView reloadData];
        [advc.tableView.mj_footer endRefreshing];
    } Failure:^(NSError *error) {
        [advc.tableView.mj_footer endRefreshing];
        NSLog(@"%@", error);
    }];
    
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.rollingLabel.hidden = YES;
    [self.rollingLabel stopTimer];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
